<template>
  <div class="wrap-container">
    <div class="order_detail" v-loading="isLoading">
      <div class="order_l">
        <div class="order_top justify-end">
          <div class="order_top_r">
            <p>订单状态</p>
            <span class="order_status" v-if="details.state == 0">待使用</span>
            <span class="order_status" v-else-if="details.state == 1">已使用</span>
            <span class="order_status" v-else-if="details.state == 2">已退款</span>
            <span class="order_status" v-if="details.state == 3">已过期</span>
            <span class="order_status" v-if="details.state == 4">部分退款</span>
          </div>
        </div>
        <div class="order_item">
          <p class="order_tit">优惠券主订单详情</p>
          <div class="order_table">
            <el-table :data="tableData" border>
              <el-table-column label="订单编号" prop="orderNo" align="center" />
              <el-table-column label="优惠券类型" prop="siteName" align="center">
                <template #default="{ row }">
                  <template v-if="row.type == 1">
                    <div v-for="item in dict?.type?.discount_type" :key="item.value">
                      <div v-if="item.value == String(row.discountType)">
                        {{ item.label }}
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <div v-if="row.cardType == 1">次卡</div>
                    <div v-else-if="row.cardType == 2">周卡</div>
                    <div v-else-if="row.cardType == 3">月卡</div>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="使用条件" align="center">
                <template #default="{ row }">
                  <template v-if="row.type == 1">
                    <span v-if="row.discountType == 3"
                      >满{{ row.useAmount }}减{{ row.moneyAmount }}</span
                    >
                    <span v-else>无门槛</span>
                  </template>
                  <template v-else>
                    <span
                      >{{ row.expirationTime }}前{{
                        row.applyStadiumType == 1 ? '全部场馆' : '指定场馆'
                      }}可用</span
                    >
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="优惠券单价" prop="amount" align="center" />
              <el-table-column label="购买数量" prop="quantity" align="center" width="100" />
              <el-table-column label="实付金额（元）" prop="payAmount" align="center" />
              <el-table-column label="支付路径" prop="payType" align="center" width="80">
                <template #default="{ row }">
                  <div v-for="item in dict?.type?.pay_source" :key="item.value">
                    <div v-if="item.value == String(row.payType)">
                      {{ item.label }}
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="下单时间" prop="createTime" align="center" />
            </el-table>
          </div>
        </div>
        <div class="order_item">
          <p class="order_tit">优惠券子订单详情</p>
          <div class="order_table">
            <el-table :data="details.childrenList" border @selection-change="handleSelectionChange">
              <el-table-column
                type="selection"
                width="50"
                :selectable="handleDisable"
                align="center"
              >
              </el-table-column>
              <el-table-column
                label="订单编号"
                prop="couponsOrderNo"
                align="center"
                show-overflow-tooltip
              />
              <el-table-column
                label="优惠券编码"
                prop="couponsCode"
                align="center"
                :width="details.type == 1 ? 100 : 120"
              />
              <el-table-column
                label="使用状态"
                prop="paymentMoney"
                align="center"
                :width="details.type == 1 ? 90 : 120"
              >
                <template #default="{ row }">
                  <template v-if="row.useStatus == 0">
                    <span v-if="row.refundState == 0">退款中</span>
                    <span v-else-if="row.refundState == 1">退款失败</span>
                    <span v-else>待使用</span>
                  </template>
                  <span v-else-if="row.useStatus == 1">已使用</span>
                  <span v-else-if="row.useStatus == 2">已退款</span>
                  <span v-else-if="row.useStatus == 3">已过期</span>
                </template>
              </el-table-column>
              <template v-if="details.type == 1">
                <el-table-column
                  label="使用场馆"
                  prop="stadiumName"
                  align="center"
                  width="150"
                  show-overflow-tooltip
                />
                <el-table-column
                  label="关联订单"
                  prop="orderNo"
                  align="center"
                  width="180"
                  show-overflow-tooltip
                >
                  <template #default="{ row }">
                    <div
                      class="cursor-pointer text-custom-blue"
                      @click="goOrderDetail(row.orderId)"
                    >
                      {{ row.orderNo }}
                    </div>
                  </template>
                </el-table-column>
              </template>
              <el-table-column
                label="有效期"
                prop="expireTime"
                align="center"
                :width="details.type == 1 ? 155 : 180"
              />
              <el-table-column
                :label="details.type == 1 ? '使用时间' : '最近使用时间'"
                prop="useTime"
                align="center"
                :width="details.type == 1 ? 155 : 180"
              />
              <el-table-column
                label="退款时间"
                prop="refundTime"
                align="center"
                :width="details.type == 1 ? 155 : 180"
              />
              <el-table-column
                label="操作"
                prop="refundTime"
                align="center"
                width="155"
                v-if="details.type == 2"
              >
                <template #default="{ row }">
                  <el-button class="primary_text" type="text" @click="handleDetail(row.useId)"
                    >查看详情</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="flex justify-end refund_btn">
            <el-button type="primary" @click="handleRefund">退款</el-button>
          </div>
        </div>
        <div class="order_item">
          <p class="order_tit">用户信息</p>
          <div class="order_info user_info">
            <div class="info_item">
              <span class="info_label">会员姓名：</span>
              <span class="info_val">{{ userInfo.userName }}</span>
            </div>
            <div class="info_item" v-hasPermi="['sys:order:btn_show_phone']">
              <span class="info_label">联系手机：</span>
              <span class="info_val">{{ userInfo.mobile }}</span>
            </div>
            <div class="info_item">
              <span class="info_label">会员类型：</span>
              <span class="info_val" v-if="userInfo.memberType == 0">普通会员</span>
            </div>
            <div class="info_item">
              <span class="info_label">下单数量：</span>
              <span class="info_val">{{ userInfo.orderQuantity }}</span>
            </div>
            <div class="info_item">
              <span class="info_label">累计消费：</span>
              <span class="info_val">{{ userInfo.orderAmount || 0 }}（元）</span>
            </div>
            <div class="info_item">
              <span class="info_label">性别：</span>
              <span class="info_val">--</span>
            </div>
            <div class="info_item">
              <span class="info_label">身份证号：</span>
              <span class="info_val">--</span>
            </div>
          </div>
        </div>
        <div class="order_customer">
          <p class="order_tit">客诉处理</p>
          <div class="flex handle_input">
            <span class="text-sm">问题描述</span>
            <div class="w-full flex-1 ml-6">
              <editor
                v-model="issueContent"
                :min-height="108"
                :placeholderTxt="'在此输入客户反馈的问题描述'"
              />
            </div>
          </div>
          <div class="flex justify-end save_customer">
            <el-button type="primary" @click="saveDispose">保存</el-button>
          </div>
          <p class="order_tit">处理详情</p>
          <div class="order_table">
            <el-table :data="disposeList" border>
              <el-table-column label="客户诉求" align="center">
                <template #default="{ row }">
                  <div v-html="row.issueContent"></div>
                </template>
              </el-table-column>
              <el-table-column label="处理时间" prop="disposeTime" align="center" width="200" />
              <el-table-column label="处理进度" prop="times" align="center" width="300">
                <template #default="{ row }">
                  <span v-if="!row.isEdit">{{ row.disposePlan }}</span>
                  <el-input v-model="row.disposePlan" v-else></el-input>
                </template>
              </el-table-column>
              <el-table-column label="处理结果" prop="disposeResult" align="center" width="300">
                <template #default="{ row }">
                  <span v-if="!row.isEdit">{{ row.disposeResult }}</span>
                  <el-input v-model="row.disposeResult" v-else></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作员" prop="createUser" align="center" width="120" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button type="text" @click="handleAdd(scope.row)">添加</el-button>
                  <el-button type="text" @click="handleEdit(scope.row)" v-if="!scope.row.isEdit"
                    >编辑</el-button
                  >
                  <el-button
                    type="text"
                    @click="() => saveDisposeItem(scope.row)"
                    v-if="scope.row.isEdit"
                    >保存</el-button
                  >
                  <el-button
                    type="text"
                    @click="handleDel(scope.row.id, scope.$index)"
                    class="cancel_txt"
                    >取消</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="order_r">
        <div class="order_track">
          <div class="order_top">
            <div class="manage_tit">
              <div class="line"></div>
              <p>订单追踪</p>
            </div>
          </div>
          <div class="track_list" v-loading="historyLoading">
            <div class="track_item" v-for="item in recordList" :key="item.id">
              <p class="create_time">{{ item.createTime }}</p>
              <div class="track_cont">
                <p>
                  {{ item.userName }}
                  <span class="text-color-808080">{{ item.stepName }}</span>
                  <span :style="{ color: item.stepColor }">{{
                    handleHistoryTypeName(item.type)
                  }}</span>
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 退款 -->
    <el-dialog
      v-model="refundVisible"
      width="565px"
      append-to-body
      :close-on-click-modal="false"
      custom-class="dialog_center"
    >
      <template #header>
        <div class="dialog_top text-center pt-2 pb-5">
          <span class="text-xl">确认给用户{{ userInfo.userName }}的订单退款吗？</span>
        </div>
      </template>
      <div class="dialog_cont flex justify-center">
        <div class="text-color-000000 text-base">
          <div class="flex mb-1">
            <p class="text-color-808080 w-32 text-left">退款子订单编号：</p>
            <div class="ml-4">
              <p class="mb-14px" v-for="item in multipleSelection" :key="item.id">
                {{ item.couponsOrderNo }}
              </p>
            </div>
          </div>
          <div class="flex mb-1">
            <p class="text-color-808080 w-32 text-left">退款优惠券编号：</p>
            <div class="ml-4">
              <p class="mb-14px" v-for="item in multipleSelection" :key="item.id">
                {{ item.couponsCode }}
              </p>
            </div>
          </div>
          <div class="flex">
            <p class="text-color-808080 w-32 text-left">退款路径：</p>
            <div class="ml-4">
              <p>微信钱包</p>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="flex justify-between dialog_btn">
          <el-button type="primary" @click="refundVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSureRefund">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <card-use-history-dialog
      v-if="cardUseHistory"
      ref="cardUseHistoryDialog"
    ></card-use-history-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce } from 'lodash'
import { getCouponsOrderDetail, couponsRefund } from '@/api/order/coupon.js'
// import { getCouponsOperationList } from '@/api/coupon/approval'
import { getHistoryLog } from '@/api/common/sysCommon'
import { getOrderDisposeList, saveOrderDispose, delOrderDispose } from '@/api/order/order.js'
import CardUseHistoryDialog from '@/views/coupon/common/cardUseHistoryDialog.vue'
import { useDict } from '@/utils/dict'

defineOptions({
  name: 'CouponOrderDetail',
})

interface Details {
  id: number
  state: number
  type: number
  childrenList: any[]
  user: UserInfo
  [key: string]: any
}

interface UserInfo {
  userName: string
  mobile: string
  memberType: number
  orderQuantity: number
  orderAmount: number
}

interface RecordItem {
  id: number
  createTime: string
  userName: string
  stepName: string
  stepColor: string
  type: number
}

interface DisposeItem {
  id: number | null
  issueContent: string
  createUser: string
  createUserId: number
  isEdit: boolean
  disposePlan?: string
  disposeResult?: string
  disposeTime?: string
}

const { dict }: any = useDict({
  dicts: [],
})
const { proxy } = getCurrentInstance() as any
const route = useRoute()
const router = useRouter()

const orderId = ref<string | null>(null)
const details = ref<Details>({} as Details)
const userInfo = ref<UserInfo>({} as UserInfo) //订单用户信息
const tableData = ref<any[]>([])
const handleList = ref<any[]>([])
const disposeList = ref<DisposeItem[]>([])
const issueContent = ref('')
const recordList = ref<RecordItem[]>([])
const refundVisible = ref(false)
const multipleSelection = ref<any[]>([]) //表格多选的值
const cardUseHistory = ref(false)
const isLoading = ref(false)
const historyLoading = ref(false)

// 获取数据
const getData = async () => {
  isLoading.value = true
  try {
    const { data } = await getCouponsOrderDetail(orderId.value)
    details.value = data
    isLoading.value = false
    tableData.value = [details.value]
    userInfo.value = details.value?.user || {}
    getRecord()
  } catch (error) {
    isLoading.value = false
    console.error(error)
  }
}

// 获取优惠券操作记录
const getRecord = async () => {
  historyLoading.value = true
  try {
    const { data } = await getHistoryLog({
      otherId: orderId.value,
    })
    recordList.value = data
    historyLoading.value = false
  } catch (error) {
    historyLoading.value = false
    console.error(error)
  }
}

// 子订单选择禁用
const handleDisable = (row: any, index: number) => {
  if (row.useStatus == 1 || row.useStatus == 2 || row.refundState == 0) {
    return false
  } else {
    return true
  }
}

// 子订单选择
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

// 退款
const handleRefund = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error('请先选择需要退款的订单')
    return
  }
  refundVisible.value = true
}

// 确认退款
const handleSureRefund = async () => {
  try {
    const childIds = multipleSelection.value.map((item: any) => item.id)
    const res = await couponsRefund({ id: details.value.id, childIds })
    ElMessage.success(res.msg)
    refundVisible.value = false
    getData()
  } catch (error) {
    console.error(error)
  }
}

// 子订单查看详情
const handleDetail = (id: number) => {
  console.log(id)
  cardUseHistory.value = true
  // 使用 nextTick 确保 DOM 更新后再调用
  setTimeout(() => {
    const cardUseHistoryDialog: any = proxy.$refs.cardUseHistoryDialog
    if (cardUseHistoryDialog) {
      cardUseHistoryDialog.init(id)
    }
  }, 0)
}

// 关联订单跳转至订单详情
const goOrderDetail = (id: number) => {
  router.push({
    path: '/order/detail',
    query: { id },
  })
}

// 获取客户诉求列表
const getDispose = async () => {
  try {
    const { data } = await getOrderDisposeList({ orderId: orderId.value })
    disposeList.value = data
    disposeList.value.forEach((item) => {
      item.isEdit = false
    })
  } catch (error) {
    console.error(error)
  }
}

// 添加客户诉求处理
const handleAdd = (row: DisposeItem) => {
  if (disposeList.value.some((item) => item.isEdit == true)) {
    ElMessage.error('请先保存编辑中的数据')
    return
  }
  disposeList.value.push({
    id: null,
    issueContent: row.issueContent,
    createUser: proxy.$store.state.user.name,
    createUserId: proxy.$store.state.user.id,
    isEdit: true,
  })
}

// 编辑客户诉求处理
const handleEdit = (row: DisposeItem) => {
  row.isEdit = true
}

// 保存客户诉求
const saveDispose = debounce(
  async () => {
    try {
      const params: any = {
        orderId: orderId.value,
        issueContent: issueContent.value,
        createUser: proxy.$store.state.user.name,
        createUserId: proxy.$store.state.user.id,
      }
      const res = await saveOrderDispose(params)
      ElMessage.success(res.msg)
      issueContent.value = ''
      getDispose()
    } catch (e) {
      ElMessage.error((e as any) || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 保存客户诉求单项
const saveDisposeItem = debounce(
  async (row: DisposeItem) => {
    try {
      const params: any = {
        orderId: orderId.value,
        issueContent: row.issueContent,
        createUser: proxy.$store.state.user.name,
        createUserId: proxy.$store.state.user.id,
        id: row.id,
        disposePlan: row.disposePlan,
        disposeResult: row.disposeResult,
      }
      const res = await saveOrderDispose(params)
      ElMessage.success(res.msg)
      getDispose()
    } catch (e) {
      ElMessage.error((e as any) || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 删除客户诉求处理
const handleDel = (id: number, index: number) => {
  if (id != null) {
    ElMessageBox.confirm('是否确认删除选中的数据项？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res = await delOrderDispose(id)
          disposeList.value.splice(index, 1)
          ElMessage.success('删除成功')
        } catch (error) {
          console.error(error)
        }
      })
      .catch(() => {})
  } else {
    disposeList.value.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

// 操作历史
const handleHistoryTypeName = (val: number) => {
  let str = '未知'
  proxy.dict?.type?.history_type.forEach((item: any) => {
    if (item.value == String(val)) {
      str = item.label
    }
  })
  return str
}

onMounted(() => {
  orderId.value = route.query.id as string
  getData()
  getDispose()
})
</script>

<style lang="scss" scoped>
.order_detail {
  display: flex;
  .order_l {
    background: #fff;
    padding: 15px 15px 30px;
    flex: 1;
    width: 100%;
    height: calc(100vh - 80px);
    overflow-y: auto;
  }
  .order_item {
    margin-bottom: 30px;
    .refund_btn {
      margin-top: 26px;
      padding-right: 42px;
      padding-bottom: 40px;
      border-bottom: 1px solid #e5e5e5;
      .el-button {
        width: 80px;
        height: 33px;
        line-height: 33px;
        padding: 0;
      }
    }
  }
  .order_tit {
    font-size: 14px;
    line-height: 21px;
    margin-bottom: 13px;
  }
  .order_top {
    display: flex;
    height: 33px;
    margin-bottom: 20px;
    .order_top_r {
      display: flex;
      align-items: flex-end;
      p {
        font-size: 16px;
        line-height: 24px;
      }
      span {
        color: #2590fa;
        font-size: 14px;
        line-height: 21px;
      }
      .order_status {
        font-size: 22px;
        line-height: 32px;
        margin-left: 15px;
      }
      img {
        width: 15px;
        height: 15px;
        margin-right: 7px;
      }
    }
  }
  .order_info {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .flex_box {
      .info_item {
        margin-bottom: 16px;
      }
    }
    .info_item {
      // width: 20%;
      margin-right: 65px;
      font-size: 14px;
      min-width: 160px;
      .info_label {
        color: #808080;
        margin-right: 10px;
        line-height: 21px;
      }
      .info_val {
        line-height: 21px;
      }
      .order_remark {
        padding: 14px 12px;
        border: 1px solid #a6a6a6;
        width: 859px;
        min-height: 89px;
        line-height: 21px;
        box-sizing: border-box;
      }
    }
  }
  .order_table {
    padding: 0 11px 0 0;
    :deep(.el-table) {
      th {
        height: 36px;
        padding: 0;
      }
      th,
      td {
        font-size: 14px;
      }
      .el-button {
        padding: 0;
        &.cancel_txt {
          color: #383838;
        }
      }
      .el-input__inner {
        text-align: center;
        color: #383838;
      }
      .el-checkbox {
        margin-left: 0;
      }
    }
  }
  :deep(.el-table--border .el-table__cell:first-child .cell) {
    padding-left: 10px;
    padding-right: 10px;
  }
  .order_customer {
    .handle_input {
      padding-right: 11px;
      span {
        color: #808080;
      }
      .el-textarea {
        flex: 1;
        margin-left: 23px;
      }
      :deep(.el-textarea__inner) {
        background: #f3f4f6;
        color: #808080;
        font-size: 14px;
        line-height: 21px;
        border: none;
        resize: none;
        color: #383838;
        border: 1px solid #e5e5e5;
        font-family: Microsoft YaHei;
      }
    }
    .save_customer {
      padding-right: 11px;
      margin-top: 13px;
      .el-button {
        width: 80px;
        height: 33px;
        padding: 0;
        line-height: 33px;
        border-radius: 6px;
      }
    }
  }
  .order_r {
    width: 384px;
    margin-left: 15px;
    .order_track {
      background: #fff;
      padding: 10px 16px;
      height: calc(100vh - 80px);
      overflow-y: auto;
      .order_top {
        margin-bottom: 0;
      }
      .track_list {
        padding: 11px 12px 0;
        .track_item {
          margin-bottom: 15px;
          .create_time {
            color: #808080;
            line-height: 18px;
            font-size: 12px;
            margin-bottom: 2px;
          }
          .track_cont {
            font-size: 14px;
            line-height: 21px;
            margin: 2px 0;
            span {
              margin: 0 8px;
            }
            .green {
              color: #00baad;
            }
            .red {
              color: #d43030;
            }
            .primary {
              color: #2a82e4;
            }
          }
        }
      }
    }
  }
  .user_info {
    row-gap: 21px;
    .info_item {
      width: 20%;
      margin-right: 0;
    }
  }
  .sure_btn {
    margin-top: 41px;
    padding-bottom: 30px;
  }
}
:deep(.ql-toolbar) {
  display: none;
}
:deep(.ql-container.ql-snow) {
  width: 100%;
  border: 1px solid #e5e5e5 !important;
  background: #f3f4f6;
  border-radius: 6px;
  .ql-editor {
    &::before {
      font-style: normal;
    }
  }
}
:deep(.el-dialog) {
  .el-dialog__body {
    padding: 0 12px;
    .dialog_cont {
      padding: 18px 0 32px;
      border-top: 1px solid #a6a6a6;
      border-bottom: 1px solid #a6a6a6;
      box-sizing: border-box;
      max-height: 600px;
      overflow-y: auto;
    }
  }
  .dialog_btn {
    padding: 12px 50px 2px;
    .el-button {
      width: 80px;
      height: 33px;
      line-height: 33px;
      padding: 0;
      background: #0988fb;
    }
  }
}
</style>
